package com.jason.fingerprint.utils;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.jason.fingerprint.R;
import com.jason.fingerprint.beans.ui.AppBean;
import com.jason.fingerprint.ui.LoadingActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: LauncherUtils
 * @Description: 本地缓存
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-12-9 16:27:04
 */
public class LauncherUtils {

    private static final String TAG = LauncherUtils.class.getSimpleName();

    public static List<AppBean> getLauncherApps(Context context) {
        PackageManager packageManager = context.getPackageManager();
        List<AppBean> beans = new ArrayList<AppBean>();
        List<PackageInfo> apps = getAllApps(context, packageManager);
        if (apps != null && !apps.isEmpty()) {
            for (int i = 0; i < apps.size(); i++) {
                PackageInfo info = apps.get(i);
                String packageName = info.applicationInfo.packageName;
                if (packageName.equals(context.getPackageName()) ||
                        packageName.equals("com.android.settings")) {
                    AppBean appBean = new AppBean();
                    appBean.icon = packageManager
                            .getApplicationIcon(info.applicationInfo);
                    appBean.name = packageManager.getApplicationLabel(
                            info.applicationInfo).toString();
                    appBean.packageName = packageName;
                    beans.add(appBean);
                }
            }
        }
        return beans;
    }


    /***
     * 获取系统内所有的应用
     * @param context
     * @return
     */
    public static List<PackageInfo> getAllApps(Context context,PackageManager packageManager) {
        List<PackageInfo> apps = new ArrayList<PackageInfo>();
        // 获取手机内所有应用
        List<PackageInfo> infos = packageManager.getInstalledPackages(0);
//        for (int i = 0; i < infos.size(); i++) {
//            PackageInfo pak = (PackageInfo) infos.get(i);
//
//            // 判断是否为非系统预装的应用程序
//            // 这里还可以添加系统自带的，这里就先不添加了，如果有需要可以自己添加
//            // if()里的值如果<=0则为自己装的程序，否则为系统工程自带
//            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
//                // 添加自己已经安装的应用程序
//                apps.add(pak);
//            }
//
//        }
        return infos;
    }

    /**
     * 创建快捷方式
     *
     * @param context 上线文菜单
     * @param title   快捷方式标题
     */
    public static void createShortCut(Context context, String title) {
        createShortCut(context, title, LoadingActivity.class);
    }


    /**
     * 创建快捷方式
     *
     * @param context 上线文菜单
     * @param title   快捷方式标题
     * @param myClass 启动的activity
     */
    public static void createShortCut(Context context, String title, Class myClass) {
        if (isShortCutExist(context, title)) {
            return;
        }
        // 创建快捷方式的Intent
        Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 不允许重复创建
        intent.putExtra("duplicate", false);
        // 需要现实的名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
        // 快捷图片
        Intent.ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(context, R.drawable.ic_launcher);
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);

        // 点击快捷图片，运行的程序主入口
        Intent targetIntent = new Intent();
        ComponentName componentName = new ComponentName(context.getPackageName(),myClass.getName());
        targetIntent.setComponent(componentName);
        targetIntent.setAction(Intent.ACTION_MAIN);
        targetIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent);
        // 发送广播。OK
        context.sendBroadcast(intent);
    }

    /***
     * 判断当前应用是否有快捷方式
     *
     * @param context 上线文菜单
     * @param title
     * @return
     */
    public static boolean isShortCutExist(Context context, String title) {
        String AUTHORITY = null;
        boolean isInstallShortcut = false;

        if (null == context || TextUtils.isEmpty(title))
            return isInstallShortcut;

        if (TextUtils.isEmpty(AUTHORITY))
            AUTHORITY = getAuthorityFromPermission(context);

        final ContentResolver cr = context.getContentResolver();

        if (!TextUtils.isEmpty(AUTHORITY)) {
            try {
                final Uri CONTENT_URI = Uri.parse(AUTHORITY);

                Cursor c = cr.query(CONTENT_URI, new String[]{"title",
                                "iconResource"}, "title=?", new String[]{title},
                        null);

                // XXX表示应用名称。
                if (c != null && c.getCount() > 0) {
                    isInstallShortcut = true;
                }
                if (null != c && !c.isClosed())
                    c.close();
            } catch (Exception e) {
                // TODO: handle exception
                Log.e("isShortCutExist", e.getMessage());
            }

        }
        return isInstallShortcut;

    }

    public static String getCurrentLauncherPackageName(Context context) {

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        ResolveInfo res = context.getPackageManager()
                .resolveActivity(intent, 0);
        if (res == null || res.activityInfo == null) {
            // should not happen. A home is always installed, isn't it?
            return "";
        }
        if (res.activityInfo.packageName.equals("android")) {
            return "";
        } else {
            return res.activityInfo.packageName;
        }
    }

    public static String getAuthorityFromPermissionDefault(Context context) {

        return getThirdAuthorityFromPermission(context,
                "com.android.launcher.permission.READ_SETTINGS");
    }

    public static String getThirdAuthorityFromPermission(Context context,
                                                         String permission) {
        if (TextUtils.isEmpty(permission)) {
            return "";
        }

        try {
            List<PackageInfo> packs = context.getPackageManager()
                    .getInstalledPackages(PackageManager.GET_PROVIDERS);
            if (packs == null) {
                return "";
            }
            for (PackageInfo pack : packs) {
                ProviderInfo[] providers = pack.providers;
                if (providers != null) {
                    for (ProviderInfo provider : providers) {
                        if (permission.equals(provider.readPermission)
                                || permission.equals(provider.writePermission)) {
                            if (!TextUtils.isEmpty(provider.authority)// 精准匹配launcher.settings，再一次验证
                                    && (provider.authority)
                                    .contains(".launcher.settings"))
                                return provider.authority;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getAuthorityFromPermission(Context context) {
        // 获取默认
        String authority = getAuthorityFromPermissionDefault(context);
        // 获取特殊第三方
        if (authority == null || authority.trim().equals("")) {
            String packageName = getCurrentLauncherPackageName(context);
            packageName += ".permission.READ_SETTINGS";
            authority = getThirdAuthorityFromPermission(context, packageName);
        }
        // 还是获取不到，直接写死
        if (TextUtils.isEmpty(authority)) {
            int sdkInt = android.os.Build.VERSION.SDK_INT;
            if (sdkInt < 8) { // Android 2.1.x(API 7)以及以下的
                authority = "com.android.launcher.settings";
            } else if (sdkInt < 19) {// Android 4.4以下
                authority = "com.android.launcher2.settings";
            } else {// 4.4以及以上
                authority = "com.android.launcher3.settings";
            }
        }
        authority = "content://" + authority + "/favorites?notify=true";
        return authority;

    }
}
